//状态变化出发所有观察对象

class Subject{
    constructor() {
        this.state = 0
        this.observers = []
    }
    getState(){
        return this.state
    }
    setState(state){
        this.state = state
        this.notify()
    }
    notify(){
        this.observers.forEach(o => {
            o.update()
        })
    }
    addSub (o){
        this.observers.push(o)
    }
}

class Observer{
    constructor(name,subject) {
        this.name = name
        this.subject =  subject
        this.subject.addSub(this)
    }
    update(){
        console.log(`${this.name} update,state: ${this.subject.getState()}`)
    }
}

let  s = new Subject()
let  o = new Observer('第一个',s)
let  b = new Observer('第二个',s)
s.setState(1)
s.setState(3)
